;layui.define(["table","form","tree",'xmSelect'], function(exports) {
    var $ = layui.$
        ,table = layui.table
        ,form = layui.form
        ,tableId = "cms-article-manage"
        ,searchFormId="#article-form-search"
        ,layTreeData = []
        ,jQ = jQuery.noConflict()
        ,xmSelect = layui.xmSelect;

    var appData = layui.data("sso_admin_app").xmSelectData;
    var initValue = [];
    if(appData.length != 0){
        initValue.push(appData[0].value);
        initTree(appData[0].value);
    }
    var selectDom = xmSelect.render({
        el: '#appName',
        name:'basicAppId',
        tips: '选择你要查找的应用',
        searchTips: '输入你要查找的应用',
        empty: '呀, 没有数据呢',
        filterable: false,
        clickClose: true,
        radio: true,
        initValue: initValue,
        model: {
            icon: 'hidden',
        },
        theme: {
            color: '#9c26b0',
        },
        data: appData,
        on({ arr, change, isAdd }){
            var value;
            var isExist = arr && arr.length > 0;
            if(isExist){
                value  = arr[0].value;
            }
            initTree(value);
            var field = $(searchFormId).serializeObject();
            if(isExist){
                field.basicAppId = arr[0].value;
            }
            tableIns.reload({
                where: field
            });
        }

    });

    function initTree(appId){
        var param = {};
        if(appId != null){
            param.appId = appId;
        }
        $.get("/sso/admin/cms/category/getCategoryZTree",param,function (res) {
            if(res.code == '00000'){
                layTreeData = res.data;
                var setting = {
                    view: {
                        showIcon: true,
                        showLine:true,
                        txtSelectedEnable: true,
                        fontCss : {'font-size':'20px'}
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    callback: {
                        onClick: function (event, treeId, treeNode, clickFlag) {
                            var field = $(searchFormId).serializeObject();
                            field.basicCategoryId = treeNode.id;
                            tableIns.reload({
                                where: field
                            });
                        }
                    }
                };
                jQ.fn.zTree.init($("#leftLayTreeId"), setting, layTreeData);
            }else{
                layTreeData = [];
            }
        });
    }


    var tableIns = table.render({
        id:tableId,
        elem: "#"+tableId,
        url: '/sso/admin/cms/article/list',
        method:'post',
        parseData:function (res) {
            var bool = res.code == '00000';
            var code = bool?0:1;
            return{
                "code": code, //解析接口状态
                "msg": "", //解析提示文本
                "count": res.data.total, //解析数据长度
                "data": res.data.records //解析数据列表
            }
        },
        cols: [[{
            type: "checkbox",
            fixed: "left",
            width: "4%",
        }, {
            field: "basicId",
            width: "10%",
            title: "编号",
            sort: true
        }, {
            field: "basicTitle",
            title: "标题",
            width: "20%"
        }, {
            field: "articleAuthor",
            title: "文章作者",
            width: "15%"
        },{
            field:'basicCategoryId',
            title:'所属栏目',
            width: '15%'
        }, {
            field: "createdTime",
            title: "发布时间",
            width: "15%"
        }, {
            title: "操作",
            width: "20%",
            align: "center",
            fixed: "right",
            toolbar: "#table-article-page-list-toolbar"
        }]],
        page: true,
        limit: 30,
        text: {
            none: '暂无相关数据' //默认：无数据
        },
        done:function (res, curr, count) {
            this.where ={};
            if(res.code == 401){
                layer.msg("没有操作权限,请联系管理员");
            }
            if(res.code == 1001){
                layer.open({
                    title: '提示信息'
                    ,content: '登录失效,请重新登录！',
                    yes:function(index,layero){
                        layer.close(index);
                    },
                    end: function(index, layero){
                        window.location.href="/sso/logout";
                    },
                    time:5000
                });
            }
        }
    });
    table.on("tool("+tableId+")", function (e) {
        var row = e.data;
        if ("del" === e.event){
            layer.prompt({
                formType: 0,
                title: "敏感操作，输入口令"
            }, function (value, index) {
                if(value == 'ok'){
                    layer.close(index);
                    layer.confirm('确定删除行吗？', function (t) {
                        $.get("/sso/admin/cms/article/remove",{ids:row.basicId},function(data){
                            if(data.code == '00000'){
                                e.del(), layer.close(t),layer.msg("删除成功"),tableIns.reload();
                            }else{
                                layer.close(t),layer.msg("删除失败，请重试");
                            }
                        });
                    });
                }else{
                    layer.msg('口令错误');
                }
            });
        }
        if ("edit" === e.event) {
            $(e.tr);
            layer.open({
                type: 2,
                title: "编辑用户 EDIT",
                content: '/sso/admin/user/toEditPage?id='+row.id,
                maxmin: !0,
                area: ["500px", "600px"]
            })
        }
        if("detail" === e.event){
            var url = "user/edit";
            layer.open({
                type: 2,
                title: "用户详情 DETAIL",
                content: '/sso/admin/user/toEditPage?id='+row.id+"&type=detail",
                maxmin: !0,
                area: ["500px", "450px"]
            })
        }
    });

    //监听锁定操作
    form.on('switch(userEnableSwitch)', function(obj){
        var value  = 2;
        var returnText = "用户禁用成功！";
        var tipText = '确定禁用当前用户？';
        if(obj.elem.checked){
            tipText = '确定启用当前用户？'
            returnText = "用户启用成功！";
            value = 1;
        }
        var json = JSON.parse(decodeURIComponent($(this).data('json')));
        json = table.clearCacheKey(json);
        layer.confirm(tipText,{
            icon: 3,
            title:'系统提示',
            yes: function (index) {
                $.get("/sso/admin/user/userSwitch",{enable:value,userId:json.id},function(res){
                    if(res.code == '00000'){
                        layer.close(index),layer.msg(returnText);
                    }else{
                        obj.elem.checked = !obj.elem.checked;
                        form.render();
                        layer.close(index),layer.msg(res.msg);
                    }
                });
            },
            cancel : function(index){
                var x = obj.elem.checked;
                obj.elem.checked = !x;
                form.render();
                layer.close(index);
            }
        });
    });

    //事件
    var active = {
        batchDel: function () {
            var checkStatus = table.checkStatus(tableId)
                , checkData = checkStatus.data
            var deList = []; //得到选中的数据
            if (checkData.length === 0) {
                return layer.msg('请选择数据');
            }
            checkData.forEach(function (row,index) {
                deList.push(row.basicId);
            });

            layer.prompt({
                formType: 0
                , title: '敏感操作，请验证口令'
            }, function (value, index) {
                if(value == 'ok'){
                    layer.close(index);
                    layer.confirm('确定删除吗？', function (index) {
                        $.get("/sso/admin/cms/article/remove",{ids:deList.join()},function(data,status){
                            if(data.code == '00000'){
                                tableIns.reload(tableId);
                                layer.msg("删除成功");
                            }else{
                                layer.msg("删除失败，请重试");
                            }
                        });

                    });
                }else{
                    layer.msg('口令错误');
                }

            });
        }
        , add: function () {
            var url = "cms/article/add";
            var index = layer.open({
                type: 2,
                offset: 'auto',
                title: '发布文章 ADD',
                content: '/sso/admin/forward/systemManage?url='+url,
                maxmin: true,
                area: ['50%', '60%'],
                btn: ['保存', '关闭'],
                btnAlign: 'c',
                yes:function (index, layero) {
                    var submit = layero.find('iframe').contents().find("#cms_article_add_form_submit");
                    submit.click();
                }
            });
            layer.full(index);
        },
        reload: function () {
            var field = $(searchFormId).serializeObject();
            var treeObj = jQ.fn.zTree.getZTreeObj('leftLayTreeId');
            var nodes = treeObj.getSelectedNodes();
            var basicCategoryId;
            if(nodes){
                if(nodes.length > 0){
                    basicCategoryId = nodes[0].id;
                }
            }
            field.basicCategoryId = basicCategoryId;
            field.basicAppId= selectDom.getValue("valueStr");
            tableIns.reload({
                where: field
            });
            if(!field.basicAppId){
                initTree()
            }
        },
        reset: function () {
            tableIns.reload();
            initTree()
            selectDom.setValue([]);
        }
    };
    $('.toolbar-button').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    exports("article", {});
});
